"use client"
import localStore, { LocalhostData } from "@/app/(dashboard)/common/util/LocalStorage";
import { SetFn } from "@/types"
import { SetStateAction, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"

/**用法同useState。修改后自动更新视图、自动更新到本地存储 （持久化）
 * @param key 键值
 * @param initialValue 初始值
 * @param beforeMountSet 在挂载时，给数据赋初值前，要对数据做什么 （比如原数据存储前是一个有原型的对象，取出来就是一个普通对象了，可以在这里做继承原型的事情）
 * @returns 具有持久化功能的 [state, setState]
 */
function useLocalStorage<T extends keyof LocalhostData = Extract<keyof LocalhostData, string>>(key: T, initialValue: LocalhostData[T], beforeMountSet?: (originItem: LocalhostData[T]) => LocalhostData[T]) {
    const [storedValue, setStoredValue] = useState(initialValue);
    const initialValueRef = useRef(initialValue);

    //页面挂载时，赋初值
    useLayoutEffect(() => {
        const item = localStore.getItem(key);
        if (item) {
            console.log(item);
            if (beforeMountSet) {
                const newData = beforeMountSet(item)
                setValue(newData);
            } else {
                setValue(item);
            }
        } else {
            setValue(initialValueRef.current);
        }
    }, [key]);

    /**拦截set操作*/
    const setValue = useCallback((value: SetStateAction<LocalhostData[T]>) => {
        if (typeof value === "function") {
            setStoredValue((v) => {
                const res = value(v);
                localStore.setItem(key, res);
                return res;
            });
        } else {
            localStore.setItem(key, value);
            setStoredValue(value);
        }
    }, [key, setStoredValue]);

    return [storedValue, setValue] as [typeof storedValue, SetFn<LocalhostData[T]>];
}
export default useLocalStorage